//
//  ChangeMessageViewController.m
//  cherryproduct
//
//  Created by Enter zhao on 14-8-13.
//  Copyright (c) 2014年 cherry. All rights reserved.
//

#import "ChangeMessageViewController.h"
#import "ChangViewController.h"
#import "UIImageView+AFNetworking.h"
#import "ZUIButton.h"
//#import "AssetsLibrary/AssetsLibrary.h"
#import "babyMessageViewController.h"
@interface ChangeMessageViewController ()

@end

@implementation ChangeMessageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _selfMessage = nil;
        isCover = NO;
        isLogo = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    //背景图片
    coverImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"titleBackground"]];
    coverImageView.userInteractionEnabled = YES;
    coverImageView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 164);
    coverImageView.tag = 121212;
    ZUIButton* button = [[ZUIButton alloc] initWithFrame:coverImageView.frame animate:NO];
    button.backgroundColor = [UIColor clearColor];
    [button addButtonCallBackBlock:^(id block) {
        isCover = YES;
        isLogo = NO;
        [UIView animateWithDuration:0.3f animations:^{
            changePhotoView.frame = CGRectMake(0, SCREEN_HEIGHT-145, SCREEN_WIDTH, 145);
        }];
    }];
    [coverImageView addSubview:button];
    
//    logo头像
    logoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-35, 60, 70, 70)];
    logoImageView.userInteractionEnabled = YES;
    logoImageView.image = [UIImage imageNamed:@"mainviewfuturebuttondown"];
    logoImageView.layer.cornerRadius = 35;
    logoImageView.layer.masksToBounds = YES;
    logoImageView.layer.borderWidth = 3.0;
    logoImageView.layer.borderColor = [UIColor whiteColor].CGColor;
    ZUIButton* logoButton = [[ZUIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 80) animate:YES];
    logoButton.backgroundColor = [UIColor clearColor];
    [logoButton addButtonCallBackBlock:^(id block) {
        isLogo = YES;
        isCover = NO;
        [UIView animateWithDuration:0.3f animations:^{
            changePhotoView.frame = CGRectMake(0, SCREEN_HEIGHT-145, SCREEN_WIDTH, 145);
        }];
    }];
    
    [logoImageView addSubview:logoButton];
    [coverImageView addSubview:logoImageView];
    
    [_mainScrollView addSubview:coverImageView];
    
    
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    scrollview
    self.myView.hidden = YES;
    [self setNavigationBarColor:[UIColor clearColor]];
    self.view.backgroundColor = [UIColor whiteColor];
    _mainScrollView.showsVerticalScrollIndicator = NO;
    _mainScrollView.showsHorizontalScrollIndicator = NO;
    _mainScrollView.delegate = self;
    
    _mainScrollView.frame = CGRectMake(0, 90, SCREEN_WIDTH, SCREEN_HEIGHT);
    [_mainScrollView setContentSize:CGSizeMake(320, 530)];
    
    //修改照片底部弹出
    changePhotoView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 145)];
    changePhotoView.backgroundColor = [UIColor whiteColor];
    ZUIButton* photoButton = [[ZUIButton alloc] initWithFrame:CGRectMake(16, 10, 288, 40) animate:NO];
    photoButton.backgroundColor = [UIColor colorWithRed:249.0/255.0 green:201.0/255.0 blue:19.0/255.0 alpha:1.0];
    [photoButton setTitle:@"相册" textColor:[UIColor whiteColor] textSize:16];
    [photoButton addButtonCallBackBlock:^(id button) {
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            
        }
        pickerImage.delegate = self;
        pickerImage.allowsEditing = NO;
        [self presentModalViewController:pickerImage animated:YES];
    }];
    
    ZUIButton* cameraButton = [[ZUIButton alloc] initWithFrame:CGRectMake(16, 10+40+5, 288, 40) animate:NO];
    cameraButton.backgroundColor = [UIColor colorWithRed:249.0/255.0 green:201.0/255.0 blue:19.0/255.0 alpha:1.0];
    [cameraButton setTitle:@"相机" textColor:[UIColor whiteColor] textSize:16];
    [cameraButton addButtonCallBackBlock:^(id button) {
        //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;

        UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
        picker.delegate = self;
        picker.allowsEditing = YES;//设置可编辑
        picker.sourceType = sourceType;
        [self presentModalViewController:picker animated:YES];//进入照相界面
    }];
    
    
    ZUIButton* cancelButton = [[ZUIButton alloc] initWithFrame:CGRectMake(16, 10+40 +40 +5+5, 288, 40) animate:NO];
    cancelButton.backgroundColor = [UIColor colorWithRed:249.0/255.0 green:201.0/255.0 blue:19.0/255.0 alpha:1.0];
    [cancelButton setTitle:@"取消" textColor:[UIColor grayColor] textSize:16];
    [cancelButton addButtonCallBackBlock:^(id button) {
        [UIView animateWithDuration:0.3f animations:^{
            changePhotoView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 145);
        }];
    }];
    
    [changePhotoView addSubview:photoButton];
    [changePhotoView addSubview:cameraButton];
    [changePhotoView addSubview:cancelButton];
    [self.view addSubview:changePhotoView];
    
    [self getUserData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)changeNameAction:(UIButton *)sender {
    ChangViewController* vc = [[ChangViewController alloc] init];
    [vc setLabel:_nameLabel title:@"昵称"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)changeSignAction:(UIButton *)sender {
    ChangViewController* vc = [[ChangViewController alloc] init];
    [vc setLabel:_signLabel title:@"签名"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)changeAgeAction:(UIButton *)sender {
    babyMessageViewController* vc = [[babyMessageViewController alloc] init];
    [vc setYearAndmonth:_year month:_month babyLabel:_ageLabel];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)changeRingAciton:(UIButton *)sender {
    ChangViewController* vc = [[ChangViewController alloc] init];
    [vc setLabel:_ringLabel title:@"消息提醒时间"];
    [self.navigationController pushViewController:vc animated:YES];
}


//注销
- (IBAction)logoutButtonAction:(UIButton *)sender {
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    [defaults setObject:@"" forKey:@"USERNAME"];
//    [defaults setObject:@"" forKey:@"USERPASSWORD"];
    //zsg
    [[LoginViewController shareUserInfo] setObject:@"0" forKey:KEY_HAVE_LOGIN];
    
    [self popToViewController:@"CPHomeViewController"];

}
- (void)getUserData
{
    [[HttpNewBaseService sharedClient] getRequestOperation:@"member/get_profile" paramDictionary:nil onCompletion:^(NSString *responseString) {
        @try {
            
            _selfMessage = [[NSDictionary alloc] initWithDictionary:[responseString JSONValue] copyItems:YES];;
            if ([[_selfMessage objectForKey:@"status"] intValue] == 1) {
                _nameLabel.text = [[_selfMessage objectForKey:@"data"] objectForKey:@"nickname"];
                
                NSString * str_sign = [[_selfMessage objectForKey:@"data"] objectForKey:@"sign"];
                if (str_sign && [str_sign isKindOfClass:[NSString class]]) {
                    _signLabel.text = [[_selfMessage objectForKey:@"data"] objectForKey:@"sign"];
                }
                
                _ringLabel.text = [[_selfMessage objectForKey:@"data"] objectForKey:@"warning"];
                NSString* date = [[_selfMessage objectForKey:@"data"] objectForKey:@"baby_birthday"];
                NSString* sex = [[_selfMessage objectForKey:@"data"] objectForKey:@"baby_sex"];
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
                [formatter setDateFormat:@"yyyy-MM-dd"];
                NSDate *date1=[formatter dateFromString:date];
                
                NSDate *now=[NSDate date];
                
                
                //                日期减
                NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
                unsigned int unitFlags = NSDayCalendarUnit;
                NSDateComponents *comps = [gregorian components:unitFlags fromDate:date1  toDate:now  options:0];
                int days = [comps day];
                _year = days/365;
                _month = days%365/30;
                
                _ageLabel.text = [NSString stringWithFormat:@"%@ %d岁 %d个月",sex.intValue?@"男":@"女",_year,_month];
                
                NSMutableString* stringimageurl = [[NSMutableString alloc] init];
                [stringimageurl appendString:JPG];
                [stringimageurl appendString:[[_selfMessage objectForKey:@"data"] objectForKey:@"cover"]];
                [coverImageView setImageWithURL:[NSURL URLWithString:stringimageurl] placeholderImage:nil];
                
                NSMutableString* stringimageurl1 = [[NSMutableString alloc] init];
                [stringimageurl1 appendString:JPG];
                [stringimageurl1 appendString:[[_selfMessage objectForKey:@"data"] objectForKey:@"logo"]];
                [logoImageView setImageWithURL:[NSURL URLWithString:stringimageurl1] placeholderImage:nil];
                
            }
            else
            {
                [self showAlertView:@"温馨提示" subtitle:[_selfMessage objectForKey:@"message"]];
            }
        }
        @catch (NSException *exception) {
            [self showAlertView:@"温馨提示" subtitle:@"网络通讯失败！"];
        }
        @finally {
            ;
        }
        
    } onError:^(NSError *error) {
        ;
    } onAnimated:YES];
}

#pragma -mack image
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo NS_DEPRECATED_IOS(2_0, 3_0){
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    // Recover the snapped image
    UIImage *image = [info
                      objectForKey:@"UIImagePickerControllerOriginalImage"];

    NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.png"];
    NSData *data = UIImagePNGRepresentation(image);
//    [data writeToFile:pngPath atomically:YES];
    
    // Point to Document directory
//    NSString  *testPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.png"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
//    NSString *filePath = [NSString stringWithString:[self getPath:@"image1"]];         //将图片存储到本地documents
    
    
    [fileManager createDirectoryAtPath:pngPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    [fileManager createFileAtPath:pngPath contents:data attributes:nil];
    // Write out the contents of home directory to console
    if (isLogo) {

        [[HttpNewBaseService sharedClient] postFileRequestOperation:@"member/upload_avatar" paramDictionary:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            [formData appendPartWithFileData:data name:@"photo" fileName:@"Temp.png" mimeType:@"image/png"];
        } onCompletion:^(NSString *responseString) {
            logoImageView.image = [info
                                   objectForKey:@"UIImagePickerControllerOriginalImage"];
            
            NSMutableDictionary* dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                        [responseString JSONValue][@"data"],@"logo",nil];
            [[HttpNewBaseService sharedClient] postFileRequestOperation:@"member/set_profile" paramDictionary:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            } onCompletion:^(NSString *responseString) {
                NSLog(@"%@",responseString);
            } onError:^(NSError *error) {
                
            } onAnimated:YES];

        } onError:^(NSError *error) {
            
        } onAnimated:YES];


    }
    if (isCover) {
        [[HttpNewBaseService sharedClient] postFileRequestOperation:@"member/upload_image" paramDictionary:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileURL:[NSURL fileURLWithPath:pngPath] name:@"photo" error:nil];
        } onCompletion:^(NSString *responseString) {
            coverImageView.image = [info
                                    objectForKey:@"UIImagePickerControllerOriginalImage"];
            
            
            NSMutableDictionary* dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                        [responseString JSONValue][@"data"],@"cover",nil];
            [[HttpNewBaseService sharedClient] postFileRequestOperation:@"member/set_profile" paramDictionary:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            } onCompletion:^(NSString *responseString) {
                NSLog(@"%@",responseString);
            } onError:^(NSError *error) {
                
            } onAnimated:YES];

        } onError:^(NSError *error) {
            
        } onAnimated:YES];
    }
    isLogo = NO;
    isCover = NO;

    [self dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissModalViewControllerAnimated:YES];
}

@end

















